﻿
using HMS.DataContract.Request;
using HMS.DataContract.Response;
using HMS.Web.Helpers;
using System;
using System.IO;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Drawing;
using System.Security.Principal;
using System.Security.AccessControl;
using System.Threading.Tasks;
using System.Drawing.Imaging;

namespace HMS.Web.Controllers
{
    public class AppointmentController : Controller
    {
        //
        // GET: /Appointment/

        public ActionResult Index(string clinicCode = "MC")
        {
            var client = InitializeSchedulerClient();
            var _clinic = client.GetClinicName(clinicCode);
            Clinic clinic = new Clinic();
            clinic.Id = _clinic.Id;
            clinic.Name = _clinic.Detail;
            clinic.Phone = _clinic.Phone;
            clinic.Address = _clinic.Address;
            client.Close();
            Session["Clinic"] = clinic;
            return View(clinic);
        }

        [Authorize]
        public ActionResult AppoinmentIndex()
        {
            UserInfo userInfo = (UserInfo)Session["userInfo"];
            if (userInfo.Detail == "P")
            {
                return RedirectToAction("index", "Patient");
            }
            return View(GetLocationList(userInfo.ClinicCode));
        }

        /// <summary>
        /// Method to Initialize Scheduler Client
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public SchedulerClient InitializeSchedulerClient()
        {

            var binding = new BasicHttpBinding();
            binding.SendTimeout = new TimeSpan(0, 0, 0, 0, 60000000);
            binding.OpenTimeout = new TimeSpan(0, 0, 0, 0, 10000000);
            binding.MaxReceivedMessageSize = 10000000;
            binding.ReaderQuotas.MaxStringContentLength = 10000000;
            binding.ReaderQuotas.MaxDepth = 10000000;
            binding.ReaderQuotas.MaxArrayLength = 10000000;
            var endpointPath = ConfigurationManager.AppSettings["SchedulerEndpointPath"];
            var endpoint = new EndpointAddress(endpointPath);
            var client = new SchedulerClient(binding, endpoint);
            return client;
        }

        /// <summary>
        /// Method to get list of Doctors based on LocId 
        /// </summary>
        /// <param name="LocId"></param>
        /// <returns></returns>

        [HttpPost]
        public ActionResult GetDoctorList(int LocId)
        {
            var client = InitializeSchedulerClient();
            var _lstDoctor = client.GetDoctorList(LocId);
            List<Doctor> lstDoctor = new List<Doctor>();
            foreach (var item in _lstDoctor)
            {
                Doctor doc = new Doctor();
                doc.Id = item.Id;
                doc.Detail = item.Detail;
                lstDoctor.Add(doc);
            }
            client.Close();
            return Json(lstDoctor);
        }


        [HttpPost]
        public ActionResult GetLocationList(string clinicCode)
        {
            //string sURL = "http://localhost:50914/Scheduler.svc/getLocationinfo";

            //WebRequest wrGETURL;
            //wrGETURL = WebRequest.Create(sURL);
            //wrGETURL.Method = "GET";
            //wrGETURL.ContentType = @"application/json; charset=utf-8";
            //HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;

            //Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
            //// read response stream from response object
            //StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
            //// read string from stream data
            //string res = loResponseStream.ReadToEnd();
            //var a = (List<LocationResponse>)JsonConvert.DeserializeObject(res);
            //// close the stream object
            //loResponseStream.Close();
            //// close the response object
            //webresponse.Close();
            //// assign the final result to text box
            UserInfo userInfo = (UserInfo)Session["userInfo"];

            var client = InitializeSchedulerClient();
            var _lstLocation = client.GetLocationList(clinicCode);
            List<Location> lstLocation = new List<Location>();
            foreach (var item in _lstLocation)
            {
                Location loc = new Location();
                loc.Id = item.Id;
                loc.Detail = item.Detail;
                lstLocation.Add(loc);
            }
            client.Close();
            if (Request.AcceptTypes.Contains("text/html"))
            {
                return View(lstLocation);
            }
            else if (Request.AcceptTypes.Contains("application/json"))
            {
                return Json(lstLocation);
            }
            else
            {
                return Json(lstLocation);
            }
        }

        /// <summary>
        /// Method to get monthly appointment list based on Docid, Locid, year and month
        /// </summary>
        /// <param name="DocId"></param>
        /// <param name="LocId"></param>
        /// <param name="Year"></param>
        /// <param name="Month"></param>
        /// <returns></returns>

        public ActionResult GetMonthlyAppointmentList(int DocId, int LocId, int Year, int Month)
        {
            var client = InitializeSchedulerClient();
            DateTime startDate = new DateTime(Year, Month, 1);
            DateTime endDate = startDate.AddMonths(1).AddSeconds(-1);
            UserInfo userInfo = (UserInfo)Session["userInfo"];
            var _monthltList = client.GetMonthlyAppointmentList(DocId, LocId, userInfo.ClinicId, startDate, endDate);
            List<MonthAppointmentMap> lstMonth = new List<MonthAppointmentMap>();
            foreach (var item in _monthltList)
            {
                MonthAppointmentMap map = new MonthAppointmentMap();
                map.Count = item.Count;
                map.Date = item.Date;
                map.DoctorEmail = _monthltList[0].DoctorEmail;
                map.DoctorName = _monthltList[0].DoctorName;
                map.DoctorNumber = _monthltList[0].DoctorNumber;
                lstMonth.Add(map);
            }
            client.Close();
            dynamic monthDet = new System.Dynamic.ExpandoObject();
            monthDet.AppointmentDetails = lstMonth;

            monthDet.DayOffDateList = GetDoctorDayOff(DocId, startDate, endDate);
            return Json(monthDet);
        }


        [HttpPost]
        public ActionResult GetDayAppointmentList(int DocId, int LocId, string date)
        {
            var serverDate = Convert.ToDateTime(date);
            return Json(GetDailyAppointmentList(DocId, LocId, serverDate));
        }

        [Authorize]
        public List<DailyViewModel> GetDailyAppointmentList(int DocId, int LocId, DateTime date)
        {
            DateTime startDate = date.Date.AddSeconds(1);
            DateTime endDate = date.Date.AddDays(1).AddSeconds(-1);

            //Logger.Error("Appointment time -------------------" + doctorAppointmentResponse.AppointmentDateTime);
            UserInfo userInfo = (UserInfo)Session["userInfo"];

            Clinic clinic = (Clinic)Session["Clinic"];

            var _clinicId = userInfo != null ? userInfo.ClinicId : clinic.Id;
            var client = InitializeSchedulerClient();
            var _dailyList = client.GetDailyAppointmentList(DocId, LocId, _clinicId, startDate, endDate).OrderBy(x => x.AppointmentTime.TimeOfDay).ToList();
            List<DailyViewModel> lstDaily = new List<DailyViewModel>();
            foreach (var item in _dailyList)
            {
                DailyViewModel day = new DailyViewModel();
                day.Id = item.Id;
                day.PatientId = item.PatientId;
                day.Name = item.PatientName;
                day.Phone = item.PatientNumber;
                day.Email = item.PatientEmail;
                day.AppointmentTime = item.AppointmentTime;
                day.AppointmentDateTime = item.AppointmentTime.ToString("dd/MM/yyyy hh:mm tt");
                day._ApptTime = day.AppointmentTime.ToString("HH:mm");
                Logger.Error(day.AppointmentTime);
                day.DocLocId = item.DoctorLocId;
                day.ApptStatusId = item.ApptStatusId;
                day.IsFollowUp = item.IsFollowUp;
                day.Purpose = item.Purpose;
                lstDaily.Add(day);
            }
            return lstDaily;
        }

        [Authorize]
        public ActionResult AppointmentDetail()
        {
            var docDetails = (HMS.Web.Helpers.DoctorSession)Session["DoctorDetails"];

            DoctorSession doc = (DoctorSession)docDetails;
            var dailyDetails = GetDailyAppointmentList(doc.DoctorId, doc.LocationId, doc.date);
            return View(dailyDetails);
        }

        [Authorize]
        [HttpPost]
        public ActionResult AddDoctorDetails(int DocId, int LocId, string date)
        {
            DoctorSession doc = new DoctorSession();
            doc.DoctorId = DocId;
            doc.LocationId = LocId;
            doc.date = Convert.ToDateTime(date);
            Session["DoctorDetails"] = doc;
            return Json(doc);
        }

        [Authorize]
        [HttpPost]
        public ActionResult AddDocApptIdToSession(int DoctorApptId, int patientId)
        {
            Session["DoctorApptId"] = DoctorApptId;
            Session["PatientId"] = patientId;
            return Json(DoctorApptId);
        }

        [Authorize]
        [HttpPost]
        public ActionResult NewDocAppt()
        {
            Session["DoctorApptId"] = 0;
            return Json(0);
        }


        public ActionResult EditAppointment()
        {
            var client = InitializeSchedulerClient();
            List<DoctorAppointmentResponse> docResponseList = new List<DoctorAppointmentResponse>();
            int DoctorAppointmentId = Session["DoctorApptId"] != null ? (int)Session["DoctorApptId"] : 0;
            Logger.Error("Doctor-------------------------" + DoctorAppointmentId);
            int PatientId = Session["PatientId"] != null ? (int)Session["PatientId"] : 0;
            Logger.Error("Patient-------------------------" + PatientId);
            if (DoctorAppointmentId != 0)
            {
                Logger.Error("Patient1-------------------------" + PatientId);
                docResponseList = client.GetAppointmentDetails(PatientId, DoctorAppointmentId, ((DoctorSession)Session["DoctorDetails"]).DoctorId).ToList<DoctorAppointmentResponse>();
                Session["PatientId"] = docResponseList[0].Patient.Id;
                Session["DoctorLocationId"] = docResponseList[0].DocLocId;
                foreach (var item in docResponseList)
                {
                    item._AppointmentDateTime = item.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm:tt");
                }
            }
            else
            {
                Logger.Error("Patient2-------------------------" + PatientId);
                UserInfo userInfo = (UserInfo)Session["userInfo"] != null ? (UserInfo)Session["userInfo"] : null;
                Logger.Error("userinfo-------------------------" + userInfo);
                DoctorAppointmentResponse docResponse = new DoctorAppointmentResponse();
                if (userInfo != null && userInfo.Detail == "P")
                {
                    Logger.Error("userinfo1-------------------------" + userInfo);
                    DateTime _date = new DateTime();
                    DoctorAppointmentResponse appointment = client.GetPatientById(userInfo.Id, _date);
                    if (appointment.Patient != null)
                        docResponse.Patient = appointment.Patient;
                }
                else
                {
                    Logger.Error("userinfo2-------------------------" + userInfo);
                    docResponse.Patient = new PatientResponse();
                    docResponse.Patient.DOB = DateTime.Now;
                    docResponse.Patient.Gender = new LookUp();
                    Logger.Error("userinfo2-------------------------end" + userInfo);
                }
                docResponse.AppointmentDateTime = DateTime.Now.ToLocalTime();
                Logger.Error("appptDateTime-------------------------end" + docResponse.AppointmentDateTime);
                docResponse._AppointmentDateTime = docResponse.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm");
                Logger.Error("appptDateTime-------------------------end" + docResponse._AppointmentDateTime);
                docResponseList.Add(docResponse);
                Logger.Error("added to list-------------------------end" + docResponse._AppointmentDateTime);
            }
            return View(docResponseList);
        }

        [HttpPost]
        public ActionResult SaveAppointmentDetails(DoctorAppointmentResponse doctorAppointmentResponse)
        {
            var client = InitializeSchedulerClient();
            //TimeZoneInfo timeZone2 = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
            //doctorAppointmentResponse.AppointmentDateTime = TimeZoneInfo.ConvertTime(doctorAppointmentResponse.AppointmentDateTime, timeZone2);
            //Logger.Error("Appointment time -------------------" + doctorAppointmentResponse.AppointmentDateTime);
            Logger.Error("Appointment time -------------------" + doctorAppointmentResponse._AppointmentDateTime);
            doctorAppointmentResponse.AppointmentDateTime = Convert.ToDateTime(doctorAppointmentResponse._AppointmentDateTime);
            Logger.Error("Appointment time -------------------" + doctorAppointmentResponse.AppointmentDateTime);
            UserInfo userInfo = (UserInfo)Session["userInfo"];
            if (userInfo == null)
            {
                userInfo = new UserInfo();
                userInfo.ClinicCode = "MC";
            }
            Clinic clinic = (Clinic)Session["Clinic"];
            doctorAppointmentResponse.Patient.Clinic = new ClinicResponse() { Id = clinic.Id };
            var SavedData = client.SaveAppointmentDetails(doctorAppointmentResponse, userInfo.ClinicCode);
            client.Close();
            return Json(SavedData);
        }

        [Authorize]
        [HttpPost]
        public ActionResult DeleteAppointment(int DocAppId)
        {
            var client = InitializeSchedulerClient();
            var appointment = client.DeleteAppointment(DocAppId);
            client.Close();
            return Json(appointment);
        }

        public ActionResult CaptureImages()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult SaveImage(string imageData)
        {
            AppointmentDocumentResponse appointment_doc = new AppointmentDocumentResponse();
            try
            {
                string path = ConfigurationManager.AppSettings["ImageFolder"];

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                    Logger.Error("2" + path);
                }
                string finalpath = String.Empty;

                if (Session["PatientId"] != null)
                {
                    var PatientPath = path + "/" + (int)Session["PatientId"];
                    Logger.Error("3" + PatientPath);
                    if (!Directory.Exists(PatientPath))
                        Directory.CreateDirectory(PatientPath);
                    if (Session["DoctorApptId"] != null)
                    {

                        finalpath = PatientPath + "/" + (int)Session["DoctorApptId"];
                        Logger.Error("4" + finalpath);
                        if (!Directory.Exists(finalpath))
                            Directory.CreateDirectory(finalpath);
                    }
                }
                Guid id = Guid.NewGuid();
                string fileNameWitPath = finalpath + "/" + id + ".png";
                Logger.Error("FileStreaming started" + DateTime.Now);
                using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
                {
                    using (BinaryWriter bw = new BinaryWriter(fs))
                    {
                        byte[] data = Convert.FromBase64String(imageData);
                        bw.Write(data);
                        Logger.Error("write success");
                        bw.Close();
                    }
                }
                Logger.Error("FileStreaming ended" + DateTime.Now);
                byte[] imgBytes = null;
                Logger.Error("Thumbnail Saving started" + DateTime.Now);
                using (Image photoImg = Image.FromFile(fileNameWitPath))
                {
                    Logger.Error("enter photimg");
                    // Create a Thumbnail from image with size 50x40.
                    // Change 50 and 40 with whatever size you want
                    using (Image thumbPhoto = photoImg.GetThumbnailImage(64, 64, null, new System.IntPtr()))
                    {
                        Logger.Error("enter thumbnail");
                        // The below code converts an Image object to a byte array
                        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                        {
                            thumbPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                            imgBytes = ms.ToArray();
                        }
                    }
                }
                Logger.Error("Thumbnail Saving ended" + DateTime.Now);
                string ThumbnailfileNameWitPath = finalpath + "/" + id + "_thumbnail.png";
                Logger.Error("thumbnailpath" + ThumbnailfileNameWitPath);
                Logger.Error("Thumbnail FileStreaming started" + DateTime.Now);
                using (FileStream fs = new FileStream(ThumbnailfileNameWitPath, FileMode.Create))
                {
                    using (BinaryWriter bw = new BinaryWriter(fs))
                    {
                        bw.Write(imgBytes);
                        Logger.Error("thumbnail saved");
                        bw.Close();
                    }
                }
                Logger.Error("Thumbnail FileStreaming ended" + DateTime.Now);

                AppointmentDocumentRequest appointmentDoc = new AppointmentDocumentRequest();
                appointmentDoc.DocAppointmentId = (int)Session["DoctorApptId"];
                appointmentDoc.ImageName = fileNameWitPath.Replace(path, "");
                var client = InitializeSchedulerClient();
                appointment_doc = client.SaveImage(appointmentDoc);
                client.Close();
            }
            catch (Exception ex)
            {
                Logger.Error("error message" + ex.Message);
                Logger.Error("error detail" + ex.InnerException);
            }
            return Json(appointment_doc);
        }
        [HttpPost]
        public ActionResult GetImageList(int DocApptId)
        {
            var client = InitializeSchedulerClient();
            var _imageList = client.GetImageList(DocApptId).ToList();
            List<ImageHelper> lstLookUp = new List<ImageHelper>();
            client.Close();
            foreach (var item in _imageList)
            {
                ImageHelper lookup = new ImageHelper();
                lookup.Id = item.Id;

                if (item.Detail != null && item.Detail != "" && string.IsNullOrEmpty(item.Prescription))
                {
                    lookup.ImagePath = ConfigurationManager.AppSettings["UploadFolder"] + item.Detail;
                    var img = item.Detail.Split('.');

                    if (item.Detail.EndsWith("doc") || item.Detail.EndsWith("docx"))
                    {
                        lookup.ThumbnailPath = "Images/word2013icon.png";
                    }
                    else if (item.Detail.EndsWith("xls") || item.Detail.EndsWith("xlsx"))
                    {
                        lookup.ThumbnailPath = "Images/Microsoft_Excel_2013_logo.png";
                    }
                    else if (item.Detail.EndsWith("ppt") || item.Detail.EndsWith("pptx"))
                    {
                        lookup.ThumbnailPath = "Images/PowerPoint-icon.png";
                    }
                    else if (item.Detail.EndsWith("pdf"))
                    {
                        lookup.ThumbnailPath = "Images/pdf.jpg";
                    }
                    else
                    {
                        lookup.isImage = true;
                        lookup.ThumbnailPath = ConfigurationManager.AppSettings["UploadFolder"] + img[0] + "_thumbnail.png";
                    }
                }
                else
                {
                    lookup._PrescriptionTime = item.CreatedDate.ToString("dd/MM/yyyy hh:mm tt");
                    lookup.Prescription = item.Prescription;
                }
                lstLookUp.Add(lookup);
            }
            return Json(lstLookUp);
        }
        /// <summary>
        /// Sending mail to doctor and patient on booking of appointment
        /// </summary>
        /// <param name="SavedData"></param>
        public void SendEmailforAppointmentBooked(DoctorAppointmentResponse SavedData)
        {
            GenericFunction _genericfunction = new GenericFunction();

            Clinic _clinic = (Clinic)Session["Clinic"];

            if (Session["userInfo"] != null)
            {
                HMS.DataContract.Response.UserInfo user = (HMS.DataContract.Response.UserInfo)Session["userInfo"];
                if (user.Detail == "D")
                {
                    // Mail to Doctor
                    _genericfunction.SendEmail(null, "Appointment booked : " + SavedData.Patient.Name + " " + SavedData.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm"), "Your appointment with " + SavedData.Patient.Name + " has been booked for " + SavedData.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm") + "<br/>" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "<br/>" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"], SavedData.DoctorEmail, user.ClinicCode);
                    _genericfunction.SendSMS(SavedData.DoctorPhone, _genericfunction.GenerateEncodedMessage("Your appointment with " + SavedData.Patient.Name + " has been booked for " + SavedData.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm") + "\n" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "\n" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"]), user.ClinicCode);
                    // Mail to Patient

                    _genericfunction.SendEmail(null, "Appointment booked : " + SavedData.DoctorName + " " + SavedData.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm"), "Your appointment with " + SavedData.DoctorName + " has been booked for " + SavedData.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm") + "<br/>" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "<br/>" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"] + "<br/> Your access code is : " + SavedData.AccessCode, SavedData.Patient.Email, user.ClinicCode);
                    _genericfunction.SendSMS(SavedData.Patient.Phone, _genericfunction.GenerateEncodedMessage("Your appointment with " + SavedData.DoctorName + " has been booked for " + SavedData.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm") + "\n" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "\n" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"] + "\n Your access code is : " + SavedData.AccessCode), user.ClinicCode);

                }
            }
            else
            {
                // Mail to Doctor
                _genericfunction.SendEmail(null, "Appointment requested : " + SavedData.Patient.Name + " " + SavedData.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm"), SavedData.Patient.Name + " has requested for an appointment for " + SavedData.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm") + "<br/>" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "<br/>" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"], SavedData.DoctorEmail, "");
                _genericfunction.SendSMS(SavedData.DoctorPhone, _genericfunction.GenerateEncodedMessage(SavedData.Patient.Name + " has requested for an appointment for " + SavedData.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm") + "\n" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "\n" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"]), "");
                // Mail to Patient
                //_genericfunction.SendEmail(null, "Appointment booked : " + SavedData.DoctorName + " " + SavedData.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm"), "You have booked an appointment with " + SavedData.DoctorName + " for " + SavedData.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm"), SavedData.Patient.Email);
            }
        }

        public ActionResult GetDoctorSlots(int DocId)
        {

            var client = InitializeSchedulerClient();
            List<string> timeSlotArray = new List<string>();

            var slotList = client.GetDoctorSlots(DocId).ToList();

            for (int i = 0; i < slotList.Count(); i = i + 2)
            {
                TimeSpan fromSlot = slotList[i];
                while (fromSlot <= slotList[i + 1])
                {
                    timeSlotArray.Add(fromSlot.ToString().Substring(0, 5));
                    fromSlot = fromSlot + new TimeSpan(0, 30, 0);
                }
            }

            return Json(timeSlotArray);
        }

        public ActionResult DoctorsDayOff(int DocId, int Year, int Month)
        {
            DateTime startDate = new DateTime(Year, Month, 1);
            DateTime endDate = startDate.AddMonths(1).AddSeconds(-1);
            List<string> dayofflist = GetDoctorDayOff(DocId, startDate, endDate);
            return Json(dayofflist);
        }

        public List<string> GetDoctorDayOff(int DocId, DateTime startDate, DateTime endDate)
        {
            var client = InitializeSchedulerClient();
            var slotList = client.GetDoctorDayOffList(DocId, startDate, endDate).ToList();
            List<string> _slotList = new List<string>();
            if (slotList != null && slotList.Count > 0)
            {
                foreach (var item in slotList)
                {
                    string slot = item.ToString("dd/MM/yyyy");
                    _slotList.Add(slot);
                }
            }
            return _slotList;

        }

        [HttpPost]
        public ActionResult SaveDoctorDayOff(string dateOff, int DocId)
        {
            var client = InitializeSchedulerClient();

            bool isSaved = false;
            isSaved = client.SaveDoctorDayOff(DocId, Convert.ToDateTime(dateOff));

            return Json(isSaved);

        }

        [HttpPost]
        public ActionResult DeleteDoctorDayOff(string dateOff, int DocId)
        {
            var client = InitializeSchedulerClient();
            bool isDeleted = false;
            isDeleted = client.DeleteDoctorDayOff(DocId, Convert.ToDateTime(dateOff));
            return Json(isDeleted);

        }





        [HttpPost]
        public ActionResult GetImageListForPatient(int DocApptId)
        {
            var client = InitializeSchedulerClient();
            var _imageList = client.GetImageList(DocApptId).ToList();
            List<ImageHelper> lstLookUp = new List<ImageHelper>();
            client.Close();
            foreach (var item in _imageList)
            {
                ImageHelper lookup = new ImageHelper();
                lookup.Id = item.Id;
                if (item.Detail != null && item.Detail != "" && string.IsNullOrEmpty(item.Prescription))
                {
                    lookup.ImagePath = ConfigurationManager.AppSettings["UploadFolder"] + item.Detail;
                    var img = item.Detail.Split('.');

                    if (item.Detail.EndsWith("doc") || item.Detail.EndsWith("docx"))
                    {
                        lookup.ThumbnailPath = "Images/word2013icon.png";
                    }
                    else if (item.Detail.EndsWith("xls") || item.Detail.EndsWith("xlsx"))
                    {
                        lookup.ThumbnailPath = "Images/Microsoft_Excel_2013_logo.png";
                    }
                    else if (item.Detail.EndsWith("ppt") || item.Detail.EndsWith("pptx"))
                    {
                        lookup.ThumbnailPath = "Images/PowerPoint-icon.png";
                    }
                    else if (item.Detail.EndsWith("pdf"))
                    {
                        lookup.ThumbnailPath = "Images/pdf.jpg";
                    }
                    else
                    {
                        lookup.isImage = true;
                        lookup.ThumbnailPath = ConfigurationManager.AppSettings["UploadFolder"] + img[0] + "_thumbnail.png";
                    }
                }
                else
                {
                    lookup._PrescriptionTime = item.CreatedDate.ToString("dd/MM/yyyy hh:mm tt");
                    lookup.Prescription = item.Prescription;
                }
                lstLookUp.Add(lookup);
            }
            return Json(lstLookUp);
        }


        [Authorize]
        [HttpPost]
        public ActionResult SavePatientImage(string imageData)
        {
            string path = ConfigurationManager.AppSettings["ImageFolder"];
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            string finalpath = String.Empty;

            if (Session["PatientId"] != null)
            {
                finalpath = path + "/" + (int)Session["PatientId"];
                if (!Directory.Exists(finalpath))
                    Directory.CreateDirectory(finalpath);

            }
            Guid id = Guid.NewGuid();
            string fileNameWitPath = finalpath + "/" + id + ".png";

            using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    byte[] data = Convert.FromBase64String(imageData);
                    bw.Write(data);
                    bw.Close();
                }
            }
            byte[] imgBytes = null;
            using (Image photoImg = Image.FromFile(fileNameWitPath))
            {
                // Create a Thumbnail from image with size 50x40.
                // Change 50 and 40 with whatever size you want
                using (Image thumbPhoto = photoImg.GetThumbnailImage(64, 64, null, new System.IntPtr()))
                {
                    // The below code converts an Image object to a byte array
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        thumbPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                        imgBytes = ms.ToArray();
                    }
                }
            }

            string ThumbnailfileNameWitPath = finalpath + "/" + id + "_thumbnail.png";

            using (FileStream fs = new FileStream(ThumbnailfileNameWitPath, FileMode.Create))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    bw.Write(imgBytes);
                    bw.Close();
                }
            }


            AppointmentDocumentRequest appointmentDoc = new AppointmentDocumentRequest();
            appointmentDoc.PatientId = (int)Session["PatientId"];
            appointmentDoc.ImageName = fileNameWitPath.Replace(path, "");
            var client = InitializeSchedulerClient();
            var appointment_doc = client.SavePatientImage(appointmentDoc);
            client.Close();
            return Json(appointment_doc);
        }

        [HttpPost]
        /// <summary>
        /// Sending mail to doctor and patient on deletion of appointment
        /// </summary>
        /// <param name="SavedData"></param>
        public void SendEmailforAppointmentDeleted(DoctorAppointmentResponse docAppt)
        {
            UserInfo user = new UserInfo();
            Clinic _clinic = (Clinic)Session["Clinic"];
            if (Session["userInfo"] != null)
            {
                user = (HMS.DataContract.Response.UserInfo)Session["userInfo"];
            }
            if (docAppt != null)
            {
                GenericFunction _genericfunction = new GenericFunction();
                // Mail to Doctor
                _genericfunction.SendEmail(null, "Cancellation : " + docAppt.Patient.Name + " " + docAppt._AppointmentDateTime, "Your appointment with " + docAppt.Patient.Name + " has been cancelled for " + docAppt._AppointmentDateTime + "<br/>" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "<br/>" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"], docAppt.DoctorEmail, user.ClinicCode);
                _genericfunction.SendSMS(docAppt.DoctorPhone, _genericfunction.GenerateEncodedMessage("Your appointment with " + docAppt.Patient.Name + " has been cancelled for " + docAppt._AppointmentDateTime + "\n" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "\n" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"]), user.ClinicCode);
                // Mail to Patient
                _genericfunction.SendEmail(null, "Cancellation : " + docAppt.DoctorName + " " + docAppt._AppointmentDateTime, "Your appointment with " + docAppt.DoctorName + " has been cancelled for " + docAppt._AppointmentDateTime + "<br/>" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "<br/>" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"] + "<br/> Your access code is : " + docAppt.AccessCode, docAppt.Patient.Email, user.ClinicCode);
                _genericfunction.SendSMS(docAppt.Patient.Phone, "Your appointment with " + _genericfunction.GenerateEncodedMessage(docAppt.DoctorName + " has been cancelled for " + docAppt._AppointmentDateTime + "\n" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "\n" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"]) + "\n Your access code is : " + docAppt.AccessCode, user.ClinicCode);
            }
        }

        [HttpPost]
        public void SendEmailforAppointmentCompleted(int docApptId)
        {
            GenericFunction _genericfunction = new GenericFunction();
            Clinic _clinic = (Clinic)Session["Clinic"];
            if (Session["userInfo"] != null)
            {
                var client = InitializeSchedulerClient();
                var docLoc = client.GetAppointmentbyId(docApptId);
                client.Close();
                if (docLoc != null)
                {
                    HMS.DataContract.Response.UserInfo user = (HMS.DataContract.Response.UserInfo)Session["userInfo"];
                    if (user.Detail == "D")
                    {
                        // Mail to Patient
                        _genericfunction.SendEmail(null, "Appointment Updated : " + docLoc.DoctorName + " " + docLoc.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm"), "Your appointment with " + docLoc.DoctorName + " on " + docLoc.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm") + " has been updated" + "<br/>" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "<br/>" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"] + "<br/>Your access code is : " + docLoc.AccessCode, docLoc.Patient.Email, user.ClinicCode);
                        _genericfunction.SendSMS(docLoc.Patient.Phone, _genericfunction.GenerateEncodedMessage("Your appointment with " + docLoc.DoctorName + " on " + docLoc.AppointmentDateTime.ToString("dd/MM/yyyy HH:mm") + " has been updated" + "\n" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "\n" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"]) + "\n Your access code is : " + docLoc.AccessCode, user.ClinicCode);
                    }
                }
            }
        }

        [HttpPost]
        public void SendEmailOnPatientProfileUpdate(int patientId)
        {
            GenericFunction _genericfunction = new GenericFunction();
            Clinic _clinic = (Clinic)Session["Clinic"];
            var client = InitializeSchedulerClient();
            var docLoc = client.GetAppointmentbyPatientId(patientId);
            client.Close();
            UserInfo user = new UserInfo();
            if (Session["userInfo"] != null)
            {
                user = (HMS.DataContract.Response.UserInfo)Session["userInfo"];
                if (user.Detail == "P")
                {
                    foreach (var item in docLoc)
                    {
                        // Mail to Doctor
                        _genericfunction.SendEmail(null, item.Patient.Name + " updated profile", "Patient " + item.Patient.Name + " has updated their personal details/personal data" + "<br/>" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "<br/>" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"], item.DoctorEmail, user.ClinicCode);
                        _genericfunction.SendSMS(item.DoctorPhone, _genericfunction.GenerateEncodedMessage("Patient " + item.Patient.Name + " has updated their personal details/personal data" + "\n" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "\n" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"]), user.ClinicCode);
                    }
                }
                else
                {
                    PatientResponse patient = docLoc.FirstOrDefault().Patient;
                    _genericfunction.SendEmail(null, "Profile updated", user.UserName + " has updated your personal details/personal data. Your access code is " + docLoc.FirstOrDefault().AccessCode + "<br/>" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "<br/>" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"], patient.Email, user.ClinicCode);
                    _genericfunction.SendSMS(patient.Phone, _genericfunction.GenerateEncodedMessage(user.UserName + " has updated your personal details/personal data" + "\n" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "\n" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"]), user.ClinicCode);
                }
            }


        }



        [HttpPost]
        public void SendMonthNotification(int DocId, int LocId, int Year, int Month, string doctorName)
        {
            //TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
            //date = TimeZoneInfo.ConvertTime(date, timeZone);
            DateTime startDate = new DateTime(Year, Month, 1);
            DateTime endDate = startDate.AddMonths(1).AddSeconds(-1);

            UserInfo userInfo = (UserInfo)Session["userInfo"];
            var client = InitializeSchedulerClient();
            var _dailyList = client.GetDailyAppointmentList(DocId, LocId, userInfo.ClinicId, startDate, endDate).ToList();
            List<DailyViewModel> lstDaily = new List<DailyViewModel>();
            foreach (var item in _dailyList)
            {
                DailyViewModel day = new DailyViewModel();
                day.Name = item.PatientName;
                day.Phone = item.PatientNumber;
                day.Email = item.PatientEmail;
                day.AppointmentDateTime = item.AppointmentTime.ToString("dd/MM/yyyy hh:mm tt");
                day.Id = item.Id;
                lstDaily.Add(day);
            }
            SendNotification(lstDaily, doctorName);
            //return lstDaily;
        }





        public void SendNotification(List<DailyViewModel> dailyViewModelList, string doctorName)
        {
            GenericFunction _genericfunction = new GenericFunction();
            var client = InitializeSchedulerClient();

            Clinic _clinic = (Clinic)Session["Clinic"];
            if (Session["userInfo"] != null)
            {
                HMS.DataContract.Response.UserInfo user = (HMS.DataContract.Response.UserInfo)Session["userInfo"];

                // Mail to Patient
                if (user.Detail == "D")
                {
                    foreach (var item in dailyViewModelList)
                    {
                        var docAppt = client.GetAppointmentbyId(item.Id);
                        _genericfunction.SendEmail(null, "Reminder : Appointment ( " + doctorName + " " + item.AppointmentDateTime + ")", "You have an appointment with " + doctorName + " on " + item.AppointmentDateTime + "<br/>" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "<br/>" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"] + "<br/> Your access code is : " + docAppt.AccessCode, item.Email, user.ClinicCode);
                        _genericfunction.SendSMS(item.Phone, _genericfunction.GenerateEncodedMessage("You have an appointment with " + doctorName + " on " + item.AppointmentDateTime + "\n" + _clinic.Name + ", " + _clinic.Address + " Ph: " + _clinic.Phone + "\n" + ConfigurationManager.AppSettings[_clinic.Code.ToUpper() + "LandingPageURL"] + "\n Your access code is : " + docAppt.AccessCode), user.ClinicCode);

                    }
                }

            }
        }

        [HttpPost]
        [Authorize]
        public ActionResult SavePrescriptionText(AppointmentDocumentRequest appDoc)
        {
            var client = InitializeSchedulerClient();
            appDoc.DocAppointmentId = (Int32)Session["DoctorApptId"];
            var isSaved = client.SavePrescriptionText(appDoc);
            return Json(appDoc.DocAppointmentId);
        }
        [HttpPost]
        public ActionResult UploadImage(HttpPostedFileBase[] files, string currentPage)
        {
            if (files != null && files.Count() > 0)
            {
                foreach (var item in files)
                {
                    string fileName = item.FileName;
                    UploadFiles(item);
                }
            }
            return RedirectToAction(currentPage.Split('/')[1], currentPage.Split('/')[0]);
        }

        public void UploadFiles(HttpPostedFileBase file)
        {
            AppointmentDocumentResponse appointment_doc = new AppointmentDocumentResponse();
            try
            {
                string path = ConfigurationManager.AppSettings["UploadFolder"];

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                    Logger.Error("2" + path);
                }
                string finalpath = String.Empty;

                if (Session["PatientId"] != null)
                {
                    var PatientPath = path + "/" + (int)Session["PatientId"];
                    Logger.Error("3" + PatientPath);
                    if (Session["DoctorApptId"] != null)
                    {

                        finalpath = PatientPath + "/" + (int)Session["DoctorApptId"];
                        Logger.Error("4" + finalpath);
                    }
                    else
                    {
                        finalpath = PatientPath;
                        Logger.Error("4" + finalpath);
                    }
                }
                Guid id = Guid.NewGuid();
                string fileNameWitPath = finalpath + "/" + id + "." + file.FileName.ToString().Split('.')[1];
                Logger.Error("FileStreaming started" + DateTime.Now);

                var filePath = Path.Combine(Server.MapPath(finalpath), id + "." + file.FileName.ToString().Split('.')[1]);
                DirectoryInfo dir = new DirectoryInfo(Server.MapPath(finalpath));
                if (!dir.Exists)
                {
                    dir.Create();
                    var access = dir.GetAccessControl();
                }
                file.SaveAs(filePath);
                if (file.ContentType.ToLower().Contains("image"))
                {
                    using (Image photoImg = Image.FromStream(file.InputStream))
                    {
                        Logger.Error("enter photimg");
                        using (Image thumbPhoto = photoImg.GetThumbnailImage(64, 64, null, new System.IntPtr()))
                        {
                            Logger.Error("enter thumbnail");
                            string ThumbnailfileNameWitPath = Server.MapPath(finalpath) + "/" + id + "_thumbnail.png";
                            var pngInfo = ImageCodecInfo.GetImageEncoders().Where(codecInfo => codecInfo.MimeType == "image/png").First();

                            using (var encParams = new EncoderParameters(1))
                            {
                                long quality = 100;
                                encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                                thumbPhoto.Save(ThumbnailfileNameWitPath, pngInfo, encParams);
                            }
                        }
                    }
                }
                AppointmentDocumentRequest appointmentDoc = new AppointmentDocumentRequest();
                if (Session["DoctorApptId"] != null)
                    appointmentDoc.DocAppointmentId = (int)Session["DoctorApptId"];
                else
                    appointmentDoc.PatientId = (int)Session["PatientId"];
                appointmentDoc.ImageName = fileNameWitPath.Replace(path, "");
                var client = InitializeSchedulerClient();
                if (Session["DoctorApptId"] != null)
                    appointment_doc = client.SaveImage(appointmentDoc);
                else
                    appointment_doc = client.SavePatientImage(appointmentDoc);
                client.Close();
            }
            catch (Exception ex)
            {
                Logger.Error("error message" + ex.Message);
                Logger.Error("error detail" + ex.InnerException);
            }
            finally
            {
                // RedirectToAction("EditAppointment");

            }
            //return Json(appointment_doc);
        }
    }
}
